function getRealtimeSold() {
  // 获取所有表格数据行
  const rows = document.evaluate('//tbody[@data-testid="beast-core-table-middle-tbody"]/tr', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

  let totalSum = 0;

  // 遍历每一行
  for (let i = 0; i < rows.snapshotLength; i++) {
      const row = rows.snapshotItem(i);
      
      // 获取第一列的文本内容
      const firstColumnText = document.evaluate('./td[1]/div/span/text()', row, null, XPathResult.STRING_TYPE, null).stringValue;
      
      // 如果第一列文本为"合计"
      if (firstColumnText.trim() === "合计") {
          // 获取第5列的数字
          const fifthColumnText = document.evaluate('./td[10]/div/div/text()', row, null, XPathResult.STRING_TYPE, null).stringValue;
          const fifthColumnNumber = parseFloat(fifthColumnText.replace(/[^0-9.-]+/g, ""));
          
          // 累加到总和中
          if (!isNaN(fifthColumnNumber)) {
              totalSum += fifthColumnNumber;
          }
      }
  }

  return totalSum;
}

function getMongoDBLink() {
  try {
    const linkElement = document.evaluate(
      '//tbody/tr[.//td[2]/div[contains(text(), "MongoDB")]]/td[3]/div',
      document,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
    ).singleNodeValue;
    
    if (linkElement) {
      return linkElement.textContent.trim();
    }
    return null;
  } catch (error) {
    console.error('Error getting MongoDB link:', error);
    return null;
  }
}

function updateRealtimeSold() {
  // 检查当前URL
  if (window.location.href === 'https://seller.kuajingmaihuo.com/main/sale-manage/main' || window.location.href === 'https://agentseller.temu.com/stock/fully-mgt/sale-manage/main') {
    // 查找目标元素
    const targetDiv = document.evaluate(
      '//div[starts-with(@class, "main_sectionBetween__")]//div[starts-with(@class, "use-divider-fields_tsx_divider")]',
      document,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
    ).singleNodeValue;
    
    if (targetDiv) {
      // 检查是否已存在H3元素
      let h3 = targetDiv.parentNode.querySelector('h3');
      if (!h3) {
        // 如果不存在则创建并插入
        h3 = document.createElement('h3');
        h3.style.color = 'red';
        targetDiv.parentNode.insertBefore(h3, targetDiv);
      }
      // 更新H3内容
      h3.textContent = "本页实时销量合计: " + getRealtimeSold();
    }
  }
}

// 调价相关函数
function clickViewPriceButton() {
  const btn = document.evaluate(
    '//button[@data-testid="beast-core-button" and ./span[text()="查看并确认申报价格"]]', // 'xpath_查看并确认申报价格按钮',
    document,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
  ).singleNodeValue;
  if (btn) {
    btn.click();
    return true;
  }
  return false;
}

function selectAdjustOption() {
  const dropdown = document.evaluate(
    '//div[@data-testid="beast-core-select" and .//div[text()="调整为参考申报价格"]]', // 'xpath_下拉列表框',
    document,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
  ).singleNodeValue;
  
  if (dropdown) {
    dropdown.click();
    
    const option = document.evaluate(
      '//li[./span[text()="重新调整报价"]]', // 'xpath_重新调整报价选项',
      document,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
    ).singleNodeValue;
    
    if (option) {
      option.click();
      return true;
    }
  }
  return false;
}

async function fillInputByKeys(inputElement, value) {
  for (const char of value) {
    // 触发完整的键盘事件序列
    const keyEventInit = {
      key: char,
      code: `Digit${char}`,
      charCode: char.charCodeAt(0),
      keyCode: char.charCodeAt(0),
      bubbles: true
    };
    
    inputElement.dispatchEvent(new KeyboardEvent('keydown', keyEventInit));
    inputElement.dispatchEvent(new KeyboardEvent('keypress', keyEventInit));
    inputElement.dispatchEvent(new KeyboardEvent('keyup', keyEventInit));
    
    // 触发input事件更新值
    inputElement.value += char;
    inputElement.dispatchEvent(new Event('input', {bubbles: true}));
    
    // 添加小延时模拟人类输入节奏
    await new Promise(resolve => setTimeout(resolve, 30));
  }
  
  // 验证输入值是否正确
  const inputValue = inputElement.value;
  if (inputValue !== value) {
    console.error(`输入验证失败: 期望值 ${value}, 实际值 ${inputValue}`);
    return false;
  }
  return true;
}

// 新增函数：清空输入框的值
function clearInputValue(xpath) {
  const element = getElementByXpath(xpath);
  if (element) {
    element.value = '';
    element.dispatchEvent(new Event('input', { bubbles: true }));
    element.dispatchEvent(new Event('change', { bubbles: true }));
    return true;
  }
  return false;
}

// 新增函数：滚动到元素底部
function scrollToBottom(xpath) {
  const element = getElementByXpath(xpath);
  if (element) {
    element.scrollTop = element.scrollHeight;
    return true;
  }
  return false;
}

// 新增函数：检查序列号是否存在
function checkSerialNumberExists(xpath, serialNumber) {
  const inputs = document.evaluate(
    xpath,
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );
  
  for (let i = 0; i < inputs.snapshotLength; i++) {
    const input = inputs.snapshotItem(i);
    if (input.value === serialNumber) {
      return { exists: true };
    }
  }
  
  return { exists: false };
}

// 新增函数：获取元素数量
function getElementCount(xpath) {
  const elements = document.evaluate(
    xpath,
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );
  
  return { count: elements.snapshotLength };
}

async function calculateAndFillPrices() {
  const rows = document.evaluate(
    '//div[@data-testid="beast-core-modal-inner" and ./div[text()="调价提效建议"]]//tbody[@data-testid="beast-core-table-middle-tbody"]/tr', // 'xpath_价格表格行',
    document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
  );
  
  let success = true;
  
  for (let i = 0; i < rows.snapshotLength; i++) {
    const row = rows.snapshotItem(i);
    const refPriceElement = document.evaluate(
      './/td[2]/span/span[2]', // 'xpath_原申报价格',
      row,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
    ).singleNodeValue;
    
    const newPriceInput = document.evaluate(
      './/input[@data-testid="beast-core-inputNumber-htmlInput"]', // 'xpath_新申报价格输入框',
      row,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
    ).singleNodeValue;
    
    if (refPriceElement && newPriceInput) {
      const refPrice = parseFloat(refPriceElement.textContent);
      if (!isNaN(refPrice)) {
        const newPrice = (refPrice - 0.05).toFixed(2);
        // 模拟点击获得焦点
        newPriceInput.focus();
        newPriceInput.click();
        
        // 逐个字符输入新价格（添加延时模拟真实输入）
        newPriceInput.value = ''; // 清空原有值
        for (const char of newPrice) {
          // 触发完整的键盘事件序列
          const keyEventInit = {
            key: char,
            code: `Digit${char}`,
            charCode: char.charCodeAt(0),
            keyCode: char.charCodeAt(0),
            bubbles: true
          };
          
          newPriceInput.dispatchEvent(new KeyboardEvent('keydown', keyEventInit));
          newPriceInput.dispatchEvent(new KeyboardEvent('keypress', keyEventInit));
          newPriceInput.dispatchEvent(new KeyboardEvent('keyup', keyEventInit));
          
          // 触发input事件更新值
          newPriceInput.value += char;
          newPriceInput.dispatchEvent(new Event('input', {bubbles: true}));
          
          // 添加小延时模拟人类输入节奏
          await new Promise(resolve => setTimeout(resolve, 30));
        }
        
        // 验证输入值是否正确
        const inputValue = newPriceInput.value;
        if (inputValue !== newPrice) {
          console.error(`输入验证失败: 期望值 ${newPrice}, 实际值 ${inputValue}`);
          success = false;
        }
      } else {
        success = false;
      }
    } else {
      success = false;
    }
  }
  
  return success;
}

function submitAdjustedPrices() {
  const submitBtn = document.evaluate(
    '//button[@data-testid="beast-core-modal-ok-button" and ./span[text()="确认提交"]]', // 'xpath_确认提交按钮',
    document,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
  ).singleNodeValue;
  
  if (submitBtn) {
    submitBtn.click();
    return true;
  }
  return false;
}

// 显示调价进度提示
function showAdjustmentProgressMessage() {
  const resetButton = document.evaluate(
    '//button[@data-testid="beast-core-button" and ./span[text()="重置"]]',
    document,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
  ).singleNodeValue;
  
  if (resetButton) {
    // 检查是否已存在提示
    const existingMessage = resetButton.parentNode.querySelector('h2.adjustment-progress-message');
    if (!existingMessage) {
      const message = document.createElement('h2');
      message.className = 'adjustment-progress-message';
      message.textContent = '申报价格自动调整中...';
      message.style.color = 'orange';
      message.style.margin = '10px 0';
      resetButton.parentNode.insertBefore(message, resetButton.nextSibling);
    }
    return true;
  }
  return false;
}

// 隐藏调价进度提示
function hideAdjustmentProgressMessage() {
  const messages = document.querySelectorAll('h2.adjustment-progress-message');
  messages.forEach(msg => msg.remove());
  return true;
}


function sumRealtimeSold() {
  // 获取所有表格数据行
  const rows = document.evaluate('//tbody[@data-testid="beast-core-table-middle-tbody"]/tr', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

  let totalSum = 0;

  // 遍历每一行
  for (let i = 0; i < rows.snapshotLength; i++) {
      const row = rows.snapshotItem(i);
      
      // 获取第一列的文本内容
      const firstColumnText = document.evaluate('./td[1]/div/span/text()', row, null, XPathResult.STRING_TYPE, null).stringValue;
      
      // 如果第一列文本为"合计"
      if (firstColumnText.trim() === "合计") {
          // 获取第5列的数字
          const fifthColumnText = document.evaluate('./td[10]/div/div/text()', row, null, XPathResult.STRING_TYPE, null).stringValue;
          const fifthColumnNumber = parseFloat(fifthColumnText.replace(/[^0-9.-]+/g, ""));
          
          // 累加到总和中
          if (!isNaN(fifthColumnNumber)) {
              totalSum += fifthColumnNumber;
          }
      }
  }

  alert("实时销量合计: " + totalSum);

  console.log("实时销量合计:", totalSum);
}

function closeMessages() {
  function clickFirstButtonWithDelay() {
    // 使用 document.evaluate 查找符合 XPath 的第一个按钮
    let xpath = '//div[starts-with(@class, "new-bell_list_")]//button/span[text()="标记为已读"]/parent::button';
    let result = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

    // 获取第一个按钮
    let button = result.singleNodeValue;

    if (button) {
        // 点击按钮
        button.click();
        console.log("点击了一个按钮");

        // 每隔 1 秒再次尝试查找并点击按钮
        setTimeout(clickFirstButtonWithDelay, 1000);
    } else {
        console.log("未找到更多按钮，脚本停止");
    }
  }

  // 执行函数
  clickFirstButtonWithDelay();
}

function clickRadioButtons() {
  function processDialog() {
    try {
      // Wait for the dialog to appear
      // const dialog = await waitForElement('//div[starts-with(@class, "MDL_innerWrapper_")]');
      
      // Find the table body
      const tbody = document.evaluate(
        '//div[starts-with(@class, "MDL_innerWrapper_")]//tbody[@data-testid="beast-core-table-middle-tbody"]',
        document,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null
      ).singleNodeValue;

      if (tbody) {
        // Find all radio buttons with "我不接受" text
        const radioButtons = document.evaluate(
          './/label[@data-testid="beast-core-radio"]/div[(text()="我不接受" or text()="放弃活动" or text()="不参与活动，放弃权益" or text()="放弃" or text()="我不接受任何调价")]/parent::label',
          tbody,
          null,
          XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
          null
        );

        // Click each radio button
        for (let i = 0; i < radioButtons.snapshotLength; i++) {
          const radioButton = radioButtons.snapshotItem(i);
          radioButton.click();
          console.log('Clicked radio button:', i + 1);
        }
      } else {
        console.error('Table body not found.');
      }

      // 点击右上角的勾
      // 定义 XPath
      let xpath = '//div[contains(@class, "exceed-hit-adjust-modal_goodsItemSelected__")]/div[1]';

      // 使用 document.evaluate 获取所有匹配的元素
      let result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

      // 遍历所有匹配的元素并点击它们
      for (let i = 0; i < result.snapshotLength; i++) {
          const element = result.snapshotItem(i);
          if (element) {
              element.click();
          }
      }
    } catch (error) {
      console.error('Error:', error);
    }
  }

  processDialog();
}

function getElementByXpath(xpath, parentNode) {
    try {
        const result = document.evaluate(
            xpath, 
            parentNode || document, 
            null, 
            XPathResult.FIRST_ORDERED_NODE_TYPE, 
            null
        );
        return result.singleNodeValue;
    } catch (error) {
        console.error('XPath评估错误:', error);
        return null;
    }
}

/**
 * 点击XPath对应的元素
 * @param {string} xpath 要点击的元素的XPath表达式
 * @returns {boolean} 返回点击是否成功
 */
function clickElementByXpath(xpath, parentNode) {
    const element = getElementByXpath(xpath, parentNode);
    
    if (element) {
        element.click();
        return true;
    }
    
    console.error('要点击的元素不存在', xpath);
    return false;
}
/**
 * 点击XPath对应的元素
 * @param {string} xpath 要点击的元素的XPath表达式
 * @returns {boolean} 返回点击是否成功
 */
function triggerElementEvent(xpath, eventType, parentNode) {
    const element = getElementByXpath(xpath, parentNode);
    
    if (element) {
        var event = new Event(eventType, { bubbles: true });
        element.dispatchEvent(event);
        return true;
    }
    
    console.error('元素不存在', xpath);
    return false;
}

/**
 * 点击XPath对应的元素
 * @param {string} xpath 要点击的元素的XPath表达式
 * @returns {boolean} 返回点击是否成功
 */
async function clickElementByXpathByMouseSimulation(xpath, parentNode) {
    const element = getElementByXpath(xpath, parentNode);
    
    if (element) {
        const mouseClickEvents = ['mousedown', 'mouseup', 'click'];
        for (const event of mouseClickEvents) {
            const mouseEvent = new MouseEvent(event, {
                view: window,
                bubbles: true,
                cancelable: true,
                buttons: 1
            });
            element.dispatchEvent(mouseEvent);
            
            // Add a small delay between events
            await new Promise(resolve => setTimeout(resolve, 1000));
        }
        return true;
    }
    
    console.error('要点击的元素不存在', xpath);
    return false;
}

/**
 * 检查XPath对应的checkbox是否已选择
 * @param {string} xpath checkbox的XPath表达式
 * @returns {boolean} 返回checkbox是否选中
 * @throws {Error} 如果元素不存在或不是checkbox则抛出错误
 */
function isCheckboxSelected(xpath, parentNode) {
    const element = getElementByXpath(xpath, parentNode);
    
    if (!element) {
        throw new Error('XPath对应的元素不存在');
    }
    
    if (element.tagName !== 'INPUT' || element.type !== 'checkbox') {
        throw new Error('XPath对应的元素不是checkbox input');
    }
    
    return element.checked;
}

/**
 * 检查radio是否已选择
 * @param {string} xpath radio input的XPath
 * @returns {boolean} 是否选中
 * @throws {Error} 如果元素不存在或类型错误
 */
function isRadioSelected(xpath, parentNode) {
    const element = getElementByXpath(xpath, parentNode);
    
    if (!element) {
        throw new Error(`XPath ${xpath} 对应的元素不存在`);
    }
    
    if (element.tagName !== 'INPUT' || element.type !== 'radio') {
        throw new Error(`XPath ${xpath} 对应的元素不是radio input`);
    }
    
    return element.checked;
}

/**
 * 组合函数：检查并点击的完整流程
 * @param {string} checkboxXpath 要检查的checkbox的XPath
 * @param {string} clickXpath 要点击的元素的XPath
 * @returns {boolean} 返回操作是否成功完成
 */
function checkAndClickIfNeeded(checkboxXpath, clickXpath) {
    try {
        const isSelected = isCheckboxSelected(checkboxXpath);
        
        if (!isSelected) {
            return clickElementByXpath(clickXpath);
        }
        
        console.log('Checkbox已选中，无需操作');
        return true;
    } catch (error) {
        console.error('操作失败:', error.message);
        return false;
    }
}

// 全局变量指示收费正在进行拒绝调价处理。通过timeoutId来管理执行时间：
var checkAndRejectAdjustmentTimeoutId = null;
// 自动拒绝调价功能的定时器ID
var autoRejectIntervalId = null;
// 自动拒绝调价功能的状态
var autoRejectEnabled = false;

// 自动拒绝调价功能
function startAutoReject() {
  if (autoRejectIntervalId !== null) {
    console.log('自动拒绝调价已经在运行中');
    return;
  }
  
  console.log('启动自动拒绝调价功能');
  autoRejectIntervalId = setInterval(() => {
    // 如果当前没有正在进行的拒绝调价操作，则开始一次新的拒绝调价
    if (checkAndRejectAdjustmentTimeoutId === null) {
      // console.log('自动拒绝调价：开始新一轮拒绝调价操作');
      rejectAllAdjustment();
    } else {
      // console.log('自动拒绝调价：当前有拒绝调价操作正在进行，跳过本次操作');
    }
  }, 5000); // 每5秒检查一次
}

function stopAutoReject() {
  if (autoRejectIntervalId !== null) {
    console.log('停止自动拒绝调价功能');
    clearInterval(autoRejectIntervalId);
    autoRejectIntervalId = null;
  }
}

// 页面加载时检查自动拒绝调价设置
function checkAutoRejectSetting() {
  if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
    chrome.storage.local.get(['autoRejectAdjustment'], function(result) {
      autoRejectEnabled = result.autoRejectAdjustment === true;
      console.log('自动拒绝调价设置:', autoRejectEnabled);
      
      if (autoRejectEnabled) {
        startAutoReject();
      } else {
        stopAutoReject();
      }
    });
  } else {
    console.log('Chrome存储API不可用，无法获取自动拒绝调价设置');
    // 默认设置为关闭状态
    autoRejectEnabled = false;
    stopAutoReject();
  }
}

// 页面加载完成后检查设置
document.addEventListener('DOMContentLoaded', function() {
  checkAutoRejectSetting();
});

// 立即检查设置（针对已加载的页面）
checkAutoRejectSetting();
// 自动拒绝调价功能的定时器ID
var autoRejectIntervalId = null;
// 自动拒绝调价功能的状态
var autoRejectEnabled = false;

function rejectAllAdjustment() {
  // 有如下几种调价对话弹窗，需要分别处理：
  //   单选项"我不接受"：每个对话框选择一个条选项，出现提示框"我已知晓风险，本次不再提醒"。调价结束时点按钮"确认，放弃高优权益"。然后弹出"您确认提交吗？"，需要点击"确认"
  //   单选项"不参与活动，放弃权益"：第一次选择一个选项，出现提示框"我已知晓风险，本次不再提醒"。调价结束时点按钮"放弃参与活动"。然后弹出"确认放弃资格？"，需要点击"仍然放弃"
  //   单选项"放弃"：第一次选择一个选项，出现提示框"我已知晓风险，本次不再提醒"。调价结束时点按钮"放弃"。然后弹出"您确认提交吗？"，需要点击"确认"
  //   单选项打勾：全部取消打勾，点击按钮"确认放弃权益"。出现提示框"我已知晓风险，不再提示"，需要点击"确认"
  // 操作流程：
  //   检查调价单选提示框，如果存在并存在未勾选，则先勾选
  //   检查调价单选提示框，如果不存在checkbox，或者存在checkbox且已勾选，则点击"确定"
  //   检查结束提示框，如果存在并存在未勾选，则先勾选
  //   检查结束提示框, 如果不存在checkbox，或者存在checkbox且已勾选，则点击"确认"或者"仍然放弃"
  //   检查调价单选项，如果存在选择，则选择第一个未选择
  //   点击调价对话框的确认按钮，包括"确认，放弃高优权益", "放弃参与活动"，"放弃"，"确认放弃权益"
  //
  // 以下是代码流程，每次循环仅执行一次点击，每次点击操作后，脚本会等待 1 秒，然后再次循环：
  // ok检查提示框带checkbox标签"我已知晓风险，本次不再提醒"。如果存在，且未标签未勾选，则勾选标签"我已知晓风险，本次不再提醒"。如果标签已勾选，则点击按钮"确认"
  // ok检查提示框带checkbox标签"我已知晓风险，不再提示"。如果存在，且未标签未勾选，则勾选标签"我已知晓风险，不再提示"。如果标签已勾选，则点击按钮"确认"
  // ok检查提示框"您确认提交吗？"，如果存在，则点击按钮"确认"
  // ok检查提示框"确认放弃资格？"，如果存在，则点击按钮"仍然放弃"
  // ok检查拒绝调价按钮，如果存在且未勾选，则点击选中第一个未选择按钮，按钮xpath：//label[@data-testid="beast-core-radio"]/div[(text()="我不接受" or text()="放弃活动" or text()="不参与活动，放弃权益" or text()="放弃" or text()="我不接受任何调价")]/parent::label
  // ok检查调价打勾按钮，如果存在已勾选，则点击取消第一个已勾选按钮，按钮xpath：//div[contains(@class, "exceed-hit-adjust-modal_goodsItemSelected__")]/div[1]。然后点击按钮"确认放弃权益"。
  // ok检查对话框按钮"放弃参与活动"，如果存在，则点击该按钮
  // 检查对话框按钮"放弃参与资格"，如果存在，则点击该按钮
  // 检查对话框按钮"确认，放弃高优权益"，如果存在，则点击该按钮
  // ok检查对话框按钮"放弃"，如果存在，则点击该按钮
  // console.log('开始执行拒绝调价操作...')

  // 现在开始按照流程执行循环操作：
  function checkAndRejectAdjustment() {
    let node
    let xpath
    let result
    let tbody
    let radioButtons
    let timeout

    // console.log('执行拒绝调价操作步骤...')

    // 我已知晓风险，本次不再提醒
    const xpath_label_1 = '//label[.//span[text()="我已知晓风险，本次不再提醒"]]'
    const xpath_label_2 = '//label[.//div[text()="我已知晓风险，本次不再提醒"]]'
    let xpath_label = xpath_label_1
    let xpath_input
    node = getElementByXpath(xpath_label +'//input')
    if (!node) {
      xpath_label = xpath_label_2
      node = getElementByXpath(xpath_label +'//input')
    } 
    if (node) {
      xpath_input = xpath_label +'//input'
      if (!isCheckboxSelected(xpath_input)) {
        clickElementByXpath(xpath_label)
        console.log('点击"我已知晓风险，本次不再提醒"')
        xpath = '//div[starts-with(@class, "index-module__actions___")]//span[text()="确认"]/parent::button'
        if (getElementByXpath(xpath)) {
          clickElementByXpath(xpath)
        }
        xpath = '//div[starts-with(@class, "index-module__actions___")]//span[text()="拒绝接受价格调整建议"]/parent::button'
        if (getElementByXpath(xpath)) {
          clickElementByXpath(xpath)
        }
        checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
        return
      }
    }

    // 我已知晓风险，不再提示
    const xpath_label_3 = '//div[text()="我已知晓风险，不再提示"]/parent::label'
    xpath_input = xpath_label_3 +'//input'
    node = getElementByXpath(xpath_input)
    if (node) {
      if (!isCheckboxSelected(xpath_input)) {
        clickElementByXpath(xpath_label_3)
        console.log('点击"我已知晓风险，本次不再提醒"')
        clickElementByXpath('//div[starts-with(@class, "body-module__popover___")]//span[text()="确认"]/parent::button')
        checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
        return
      }
    }

    const xpaths_confirm_button = [
      '//div[starts-with(@class, "body-module__modal__") and .//div[starts-with(@class, "body-module__title") and text()="您确认提交吗？"]]//button[./span[text()="确认"]]',
      '//div[starts-with(@class, "PP_popoverFooter_")]//span[text()="仍然放弃"]/parent::button',
      '//div[@data-testid="beast-core-portal-main" and .//tbody/tr/td[1][text()="0"] and .//tbody/tr/td[2][text()="0"]]//div[contains(@class, "body-module__footer")]/button[./span[text()="确认"]]'
    ]
    for (let i = 0; i < xpaths_confirm_button.length; i++) {
      xpath = xpaths_confirm_button[i]
      node = getElementByXpath(xpath)
      if (node) {
        clickElementByXpath(xpath)
        console.log('点击', xpath)
        checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 5000)
        return
      }
    }

    // 揽收费用减免，点击右上角的勾
    xpath = '//div[contains(@class, "exceed-hit-adjust-modal_goodsItemSelected__")]/div[1]';
    node = getElementByXpath(xpath)
    if (node) {
      // 使用 document.evaluate 获取所有匹配的元素
      result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

      // 遍历所有匹配的元素并点击它们
      for (let i = 0; i < result.snapshotLength; i++) {
          const element = result.snapshotItem(i);
          if (element) {
              element.click();
          }
      }

      clickElementByXpath('//div[starts-with(@class, "MDL_footer_")]//span[text()="确认放弃权益"]/parent::button')
      console.log('点击"确认放弃权益"')
      checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
      return
    }

    // 流量下降，需要拒绝调价！！！是div，不是radio！！！
    //div[@data-testid="beast-core-modal-body" and .//div[contains(normalize-space(.), "请及时调价提效！")]]//div[./div/div[text()="不调整"]]

    // 逐个点击拒绝调价按钮，直到所有按钮都被点击
    xpath = '//label[@data-testid="beast-core-radio" and (.//div[text()="维持原价" or text()="我不接受" or text()="放弃活动" or text()="不参与活动，放弃权益" or text()="放弃" or text()="我不接受任何调价" or text()="不调整"])]'
    xpath_tbody = '//div[starts-with(@class, "MDL_innerWrapper_")]//tbody[@data-testid="beast-core-table-middle-tbody"]'

    // Find all radio buttons with "我不接受" text
    radioButtons = document.evaluate(
      xpath_tbody + xpath,
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
    );

    radioClicked = false
    timeout = 200
    // Click each radio button
    for (let i = 0; i < radioButtons.snapshotLength; i++) {
      const radioButton = radioButtons.snapshotItem(i);
      if (!isRadioSelected('.//input', radioButton)) {
        radioClicked = true
        radioButton.click();
        console.log('Clicked radio button:', i + 1);
        if (i == radioButtons.snapshotLength - 1) {
          timeout = 1000 // 最后一个按钮点击后，等待时间长一些
        }
        break
      }
    }

    if (radioClicked) {
      checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, timeout) // 只是点击单选按钮可以快速完成
      return
    }

    // 2件商品流量下降中，请及时调价提效！
    // 它的单选框不是input元素，而是div元素通过img元素绘制一个圆圈
    xpath = '//div[./img[contains(@src, "de9992d8d97a13a01153.png")] and .//div[text()="不调整"]]'
    // Find all radio buttons with "我不接受" text
    radioButtons = document.evaluate(
      xpath,
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
    );

    radioClicked = false
    timeout = 200
    // Click each radio button
    for (let i = 0; i < radioButtons.snapshotLength; i++) {
      const radioButton = radioButtons.snapshotItem(i);
      radioClicked = true
      radioButton.click();
      console.log('Clicked radio button:', i + 1);
      if (i == radioButtons.snapshotLength - 1) {
        timeout = 1000 // 最后一个按钮点击后，等待时间长一些
      }
      break
    }

    if (radioClicked) {
      checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, timeout) // 只是点击单选按钮可以快速完成
      return
    }

    // 以下是放弃、拒绝、或者确认按钮
    const xpaths = [
      '//div[@data-testid="beast-core-modal-body" and .//div[text()="商品降价弹窗"]]//div[starts-with(@class, "MDL_footer_")]//span[text()="确认"]/parent::button',
      '//div[starts-with(@class, "modal-content_footer__")]//span[text()="放弃参与活动"]/parent::button',
      '//div[starts-with(@class, "MDL_footer_")]//div[text()="放弃"]/parent::button',
      '//div[starts-with(@class, "MDL_footer_")]//div[text()="确认，放弃高优权益"]/parent::button',
      '//div[starts-with(@class, "MDL_footer_")]//div[text()="确认，放弃权益"]/parent::button',
      '//div[starts-with(@class, "MDL_bottom_")]//span[text()="放弃流量增长机会"]/parent::button',
      '//div[@data-testid="beast-core-modal-body" and .//div[starts-with(text(), "已勾选商品共有")]]//button[./span[text()="确认"]]',
      '//div[starts-with(@class, "MDL_footer_") and starts-with(normalize-space(.), "【商品价格调整参考】已选择调整0条")]//button[./span[text()="确认"]]',
      '//div[starts-with(@class, "MDL_footer_") and starts-with(normalize-space(.), "【商品价格调整参考】已选择接受0条")]//button[./span[text()="确认"]]',
      '//div[@data-testid="beast-core-modal" and .//span[text()="商品流量下降中"] and .//div[contains(normalize-space(.), "请及时调价提效！")]]//button[./span[text()="确认"]]',
      '//div[@data-testid="beast-core-modal" and .//div[contains(normalize-space(.), "已选择调整日常申报价") and ./span[1][text()="0"] and ./span[2][text()="0"]]]//button[./span[text()="确认"]]',
      '//div[@data-testid="beast-core-modal" and .//div[contains(normalize-space(.), "已选择调整日常申报价") and ./span[1][text()="0"] and ./span[2][text()="0"]]]//button[./span[text()="确认提交"]]'
    ]
    for (xpath of xpaths) {
      if (getElementByXpath(xpath)) {
        clickElementByXpath(xpath)
        console.log('点击', xpath)
        checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
        return
      }
    }

    // // "商品降价弹窗"，都已经拒绝了，点击"确认"
    // if (getElementByXpath('//div[@data-testid="beast-core-modal-body"]//div[text()="商品降价弹窗"]') && getElementByXpath('//div[starts-with(@class, "MDL_footer_")]//span[text()="确认"]/parent::button')) {
    //   clickElementByXpath('//div[starts-with(@class, "MDL_footer_")]//span[text()="确认"]/parent::button')
    //   console.log('点击"确认"')
    //   checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
    //   return
    // }

    // // 点击"放弃参与活动"
    // xpath = '//div[starts-with(@class, "modal-content_footer__")]//span[text()="放弃参与活动"]/parent::button'
    // node = getElementByXpath(xpath)
    // if (node) {
    //   clickElementByXpath(xpath)
    //   console.log('点击"放弃参与活动"')
    //   checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
    //   return
    // }

    // // 点击"放弃"
    // if (getElementByXpath('//div[starts-with(@class, "MDL_footer_")]//div[text()="放弃"]/parent::button')) {
    //   clickElementByXpath('//div[starts-with(@class, "MDL_footer_")]//div[text()="放弃"]/parent::button')
    //   console.log('点击"放弃"')
    //   checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
    //   return
    // }

    // // "确认，放弃高优权益"
    // if (getElementByXpath('//div[starts-with(@class, "MDL_footer_")]//div[text()="确认，放弃高优权益"]/parent::button')) {
    //   clickElementByXpath('//div[starts-with(@class, "MDL_footer_")]//div[text()="确认，放弃高优权益"]/parent::button')
    //   console.log('点击"确认，放弃高优权益"')
    //   checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
    //   return
    // }

    // // "确认，放弃权益"
    // if (getElementByXpath('//div[starts-with(@class, "MDL_footer_")]//div[text()="确认，放弃权益"]/parent::button')) {
    //   clickElementByXpath('//div[starts-with(@class, "MDL_footer_")]//div[text()="确认，放弃权益"]/parent::button')
    //   console.log('点击"确认，放弃权益"')
    //   checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
    //   return
    // }

    // // "放弃流量增长机会"
    // if (getElementByXpath('//div[starts-with(@class, "MDL_bottom_")]//span[text()="放弃流量增长机会"]/parent::button')) {
    //   clickElementByXpath('//div[starts-with(@class, "MDL_bottom_")]//span[text()="放弃流量增长机会"]/parent::button')
    //   console.log('点击"放弃流量增长机会"')
    //   checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
    //   return
    // }

    // if (getElementByXpath('//div[@data-testid="beast-core-modal-body" and .//div[starts-with(text(), "已勾选商品共有")]]//button[./span[text()="确认"]]')) {
    //   clickElementByXpath('//div[@data-testid="beast-core-modal-body" and .//div[starts-with(text(), "已勾选商品共有")]]//button[./span[text()="确认"]]')
    //   console.log('已确认商品调价')
    //   checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
    //   return
    // }

    // if (getElementByXpath('//div[starts-with(@class, "MDL_footer_") and starts-with(normalize-space(.), "【商品价格调整参考】已选择调整0条")]//button[./span[text()="确认"]]')) {
    //   clickElementByXpath('//div[starts-with(@class, "MDL_footer_") and starts-with(normalize-space(.), "【商品价格调整参考】已选择调整0条")]//button[./span[text()="确认"]]')
    //   console.log('已确认商品调价')
    //   checkAndRejectAdjustmentTimeoutId = setTimeout(checkAndRejectAdjustment, 1000)
    //   return
    // }

    checkAndRejectAdjustmentTimeoutId = null;
    // console.log('拒绝调价操作已完成或没有更多操作需要执行')

  }

  checkAndRejectAdjustment()
}

// 新增previewAllPages相关函数
// function clickElementByXpath(xpath) {
//   const element = document.evaluate(
//     xpath,
//     document,
//     null,
//     XPathResult.FIRST_ORDERED_NODE_TYPE,
//     null
//   ).singleNodeValue;

//   if (element) {
//     element.click();
//     return true;
//   }
//   return false;
// }

function previewHomePageProcess() {
  // 检查并点击"我知道了"按钮
  clickElementByXpath('//button/span[text()="我知道了"]/parent::button');

  // 循环处理"继续缴费"按钮
  let continuePayButtons;
  do {
    continuePayButtons = document.evaluate(
      '//button/span[text()="继续缴费"]/parent::button',
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
    );

    if (continuePayButtons.snapshotLength > 0) {
      const button = continuePayButtons.snapshotItem(0);
      if (button) {
        button.click();
      }

      // 点击取消按钮
      clickElementByXpath('//div[text()="选择缴费方式"]/parent::div//button/span[text()="取消"]/parent::button');
    }
  } while (continuePayButtons.snapshotLength > 0);

  // 循环处理"确认缴费"按钮
  let confirmPayButtons;
  do {
    confirmPayButtons = document.evaluate(
      '//button/span[text()="确认缴费"]/parent::button',
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
    );

    // 如果只有一个元素，则不继续循环
    if (confirmPayButtons.snapshotLength <= 1) {
      break;
    }

    if (confirmPayButtons.snapshotLength > 0) {
      const button = confirmPayButtons.snapshotItem(0);
      if (button) {
        button.click();
      }

      // 点击取消按钮
      clickElementByXpath('//div[text()="选择缴费方式"]/parent::div//button/span[text()="取消"]/parent::button');
    }
  } while (confirmPayButtons.snapshotLength > 1); // 大于1时继续循环

  // 检查并点击checkbox
  clickElementByXpath('//div[@data-testid="beast-core-checkbox-checkIcon"]');

  // 检查并点击进入按钮
  clickElementByXpath('//div[starts-with(text(),"进入") or starts-with(text(),"跨境Temu商家中心")]');

  return true;
}

// 新增函数：设置输入框的值
async function setInputValue(xpath) {
  const element = getElementByXpath(xpath);
  if (element) {
    // 获取浏览器自动填充的值
    const autofillValue = element.value;
    const value = autofillValue;
    console.log('Browser autofill value:', xpath, autofillValue);
    
    // 模拟点击获得焦点
    element.focus();
    element.click();
    
    // 逐个字符输入新价格（添加延时模拟真实输入）
    element.value = ''; // 清空原有值
    for (const char of value) {
      // 触发完整的键盘事件序列
      const keyEventInit = {
        key: char,
        code: `Digit${char}`,
        charCode: char.charCodeAt(0),
        keyCode: char.charCodeAt(0),
        bubbles: true
      };
      
      element.dispatchEvent(new KeyboardEvent('keydown', keyEventInit));
      element.dispatchEvent(new KeyboardEvent('keypress', keyEventInit));
      element.dispatchEvent(new KeyboardEvent('keyup', keyEventInit));
      
      // 触发input事件更新值
      element.value += char;
      element.dispatchEvent(new Event('input', {bubbles: true}));
      
      // 添加小延时模拟人类输入节奏
      await new Promise(resolve => setTimeout(resolve, 30));
    }
    
    // 触发事件确保页面能检测到值的变化
    element.dispatchEvent(new Event('change', { bubbles: true }));
    return true;
  }
  return false;
}

function previewGetPendingCount() {
  const pendingElement = document.evaluate(
    '//div[@data-testid="beast-core-tab-itemLabel-wrapper"]/div[@data-testid="beast-core-tab-itemLabel" and starts-with(text(), "待创建")]',
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
  ).singleNodeValue;

  if (pendingElement) {
    const text = pendingElement.textContent;
    const match = text.match(/待创建\((\d+)\)/);
    if (match && match[1]) {
      return { count: parseInt(match[1], 10) };
    }
  }
  return { count: 0 };
}

function previewGetAdjustmentCount() {
  const pendingElement = document.evaluate(
    '//div[@data-testid="beast-core-tab-itemLabel-wrapper"]/div[@data-testid="beast-core-tab-itemLabel" and starts-with(text(), "待卖家确认")]',
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
  ).singleNodeValue;

  if (pendingElement) {
    const text = pendingElement.textContent;
    const match = text.match(/待卖家确认\((\d+)\)/);
    if (match && match[1]) {
      return { count: parseInt(match[1], 10) };
    }
  }
  return { count: 0 };
}

function previewHandleGoodsListModal() {
  // 检查并点击"去查看"按钮
  let success = clickElementByXpath('//div[@data-testid="beast-core-modal-container"]//div[starts-with(@class,"modal-todo-alert_handleItem") and .//div[contains(text(), "个商品已获得资质补贴活动参与资格")]]//button[.//span[text()="去查看"]]');

  // 如果没有找到，则检查并点击"去处理"按钮
  if (!success) {
    success = clickElementByXpath('//div[@data-testid="beast-core-modal-container"]//div[starts-with(@class,"modal-todo-alert_handleItem") and .//div[contains(text(), "个热销款待更新视频")]]//button[.//span[text()="去处理"]]');
  }

  return success;
}

function previewCheckPriceFeedback() {
  const allRows = document.evaluate(
    '//tbody[@data-testid="beast-core-table-middle-tbody"]/tr',
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );

  const successRows = document.evaluate(
    '//tbody[@data-testid="beast-core-table-middle-tbody"]/tr//div[contains(text(), "跟价成功")]',
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );

  return { 
    hasPending: allRows.snapshotLength !== successRows.snapshotLength 
  };
}

function previewAlertUser(data) {
  alert(data.message);
  return true;
}

function getPricesToConfirm() { 
  const pendingElement = document.evaluate(
    '//div[starts-with(@class,"use-quick-field_tsx_container")]//div[./span[text()="价格待确认"]]/span[2]',
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
  ).singleNodeValue;

  if (pendingElement) {
    const text = pendingElement.textContent;
    if (text) {
      return { count: parseInt(text) };
    }
  }
  return { count: 0 };
}

// 消息处理
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('Received message:', request);
  if (request.action === 'getMongoDBLink') {
    const link = getMongoDBLink();
    sendResponse({ link });
  } else if (request.action === 'clickRadioButtons') {
    clickRadioButtons();
    sendResponse({ success: true });
  } else if (request.action === 'closeMessages') {
    closeMessages();
    sendResponse({ success: true });
  } else if (request.action === 'sumRealtimeSold') {
    sumRealtimeSold();
    sendResponse({ success: true });
  } else if (request.action === 'rejectAllAdjustment') {
    rejectAllAdjustment();
    sendResponse({ success: true });
  } else if (request.action === 'checkIsRejectingAdjustment') {
    sendResponse({ isRejecting: checkAndRejectAdjustmentTimeoutId !== null });
  } else if (request.action === 'autoRejectSettingChanged') {
    autoRejectEnabled = request.enabled === true;
    console.log('自动拒绝调价设置已更改:', autoRejectEnabled);
    
    if (autoRejectEnabled) {
      startAutoReject();
    } else {
      stopAutoReject();
    }
    sendResponse({ success: true });
  } else if (request.action === 'clickViewPriceButton') {
    sendResponse({success: clickViewPriceButton()});
  } else if (request.action === 'selectAdjustOption') {
    sendResponse({success: selectAdjustOption()});
  } else if (request.action === 'calculateAndFillPrices') {
    calculateAndFillPrices().then(success => {
      sendResponse({success});
    });
    return true; // 保持消息端口开放
  } else if (request.action === 'submitAdjustedPrices') {
    sendResponse({success: submitAdjustedPrices()});
  } else if (request.action === 'priceAdjustmentComplete') {
    alert(`价格调整完成！已调整${request.adjustedCount}个商品的价格`);
  } else if (request.action === 'showAdjustmentInProgress') {
    sendResponse({success: showAdjustmentProgressMessage()});
  } else if (request.action === 'hideAdjustmentInProgress') {
    sendResponse({success: hideAdjustmentProgressMessage()});
  } else if (request.action === 'triggerElementEvent') {
    const success = triggerElementEvent(request.xpath, request.eventType);
    sendResponse({ success });
  } else if (request.action === 'clickElement') {
    const success = clickElementByXpath(request.xpath);
    sendResponse({ success });
  } else if (request.action === 'clickElementByMouseSimulation') {
    clickElementByXpathByMouseSimulation(request.xpath).then(success => {
      sendResponse({ success });
    });
    return true; // 保持消息端口开放
  } else if (request.action === 'clearInputValue') {
    const success = clearInputValue(request.xpath);
    sendResponse({ success });
  } else if (request.action === 'fillInputByKeys') {
    const element = getElementByXpath(request.xpath);
    if (element) {
      fillInputByKeys(element, request.value).then(success => {
        sendResponse({ success });
      });
      return true; // 保持消息端口开放
    } else {
      sendResponse({ success: false });
    }
  } else if (request.action === 'scrollToBottom') {
    const success = scrollToBottom(request.xpath);
    sendResponse({ success });
  } else if (request.action === 'checkSerialNumberExists') {
    const result = checkSerialNumberExists(request.xpath, request.serialNumber);
    sendResponse(result);
  } else if (request.action === 'getElementCount') {
    const result = getElementCount(request.xpath);
    sendResponse(result);
  } else if (request.action === 'previewHomePageProcess') {
    const success = previewHomePageProcess();
    sendResponse({ success });
  } else if (request.action === 'previewGetPendingCount') {
    const result = previewGetPendingCount();
    sendResponse(result);
  } else if (request.action === 'previewGetAdjustmentCount') {
    const count = previewGetAdjustmentCount().count;
    sendResponse({ count });
  } else if (request.action === 'previewHandleGoodsListModal') {
    const success = previewHandleGoodsListModal();
    sendResponse({ success });
  } else if (request.action === 'previewGetPricesToConfirm') {
    // 产品生命周期中价格待确认数量
    const result = getPricesToConfirm();
    sendResponse(result);
  } else if (request.action === 'previewCheckPriceFeedback') {
    const result = previewCheckPriceFeedback();
    sendResponse(result);
  } else if (request.action === 'previewAlertUser') {
    const success = previewAlertUser(request);
    sendResponse({ success });
  } else if (request.action === 'setInputValue') {
    const success = setInputValue(request.xpath);
    sendResponse({ success });
  }
});

/**
 * 处理活动营销日志页面的数据
 * 
 * 该函数用于在活动营销日志页面中为每个SKU添加成本价和毛利率信息
 * 支持两种不同的页面布局：活动日志页面和活动详情页面
 * 通过Chrome扩展消息传递机制获取SKU的成本价，并计算毛利率
 * 根据毛利率高低显示不同颜色（大于10%为绿色，否则为红色）
 */
async function processMarketingActivityLog() {
  // 定义表格中各列的索引和XPath，不同页面有不同的结构
  let tdIdx_skc;                                      // SKC信息所在列索引
  let tdIdx_sku_main, tdIdx_regularPrice_main, tdIdx_activityPrice_main;  // 主行中各列索引
  let tdIdx_sku_sub, tdIdx_regularPrice_sub, tdIdx_activityPrice_sub;     // 子行中各列索引
  let xpath_skc, xpath_sku, xpath_regularPrice, xpath_activityPrice, xpath_activityPrice_2;      // 各元素的XPath

  xpath_span_cost = '//span[contains(text(), "成本")]';
  // 处理活动营销日志页面 - 固定列结构
  if (window.location.href.startsWith("https://agentseller.temu.com/activity/marketing-activity/log")) {
    // 设置活动日志页面的列索引（固定结构）
    tdIdx_skc = 3;                    // SKC信息在第3列
    tdIdx_sku_main = 4;               // 主行中SKU在第4列
    tdIdx_regularPrice_main = 5;      // 主行中日常申报价在第5列
    tdIdx_activityPrice_main = 6;     // 主行中活动申报价在第6列
    tdIdx_sku_sub = 1;                // 子行中SKU在第1列
    tdIdx_regularPrice_sub = 2;       // 子行中日常申报价在第2列
    tdIdx_activityPrice_sub = 3;      // 子行中活动申报价在第3列

    // 设置各元素在单元格内的XPath
    xpath_skc = '/div/div/div[1]';            // SKC信息元素路径
    xpath_sku = '/div/div/div';               // SKU信息元素路径
    xpath_regularPrice = '/div/span/span[2]'; // 日常申报价元素路径
    xpath_activityPrice = '/div/div/span/span[2]'; // 活动申报价元素路径
    xpath_activityPrice_2 = '//div[./span[contains(text(), "活动门槛价")]]/span[2]/span[2]'; // 另一种活动申报价元素路径，包含门槛价和最优流量价
  // 处理活动详情页面 - 动态列结构
  } else if (window.location.href.startsWith("https://agentseller.temu.com/activity/marketing-activity/detail-new")) {
    // 从表头动态获取各列的索引，因为详情页面的列顺序可能会变化
    const headers = document.evaluate(
      '//thead[@data-testid="beast-core-table-middle-thead"]/tr/th',
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
    );
    
    // 遍历表头，根据列名确定各列的索引
    for (let i = 0; i < headers.snapshotLength; i++) {
      const headerText = headers.snapshotItem(i).textContent.trim();
      if (headerText === "SKC信息") {
        tdIdx_skc = i + 1;                // XPath索引从1开始，而不是0
      } else if (headerText === "SKU属性集") {
        tdIdx_sku_main = i + 1;           // SKU属性集列索引
      } else if (headerText.includes("日常") && headerText.includes("申报")) {
        tdIdx_regularPrice_main = i + 1;  // 日常申报价格列索引
      } else if (headerText.includes("参考申报价")) {
        tdIdx_activityPrice_main = i + 1; // 参考申报价格列索引
      }
    }
    
    // 子行的列索引是固定的
    tdIdx_sku_sub = 1;                // 子行中SKU在第1列
    tdIdx_regularPrice_sub = 2;       // 子行中日常申报价在第2列
    tdIdx_activityPrice_sub = 3;      // 子行中活动申报价在第3列

    // 详情页面中各元素的XPath与日志页面略有不同
    xpath_skc = '/div/div[1]';             // SKC信息元素路径
    xpath_sku = '/div/div[2]';             // SKU信息元素路径
    xpath_regularPrice = '/span/span[2]';  // 日常申报价元素路径
    xpath_activityPrice = '/div/span/span[2]'; // 活动申报价元素路径
    xpath_activityPrice_2 = '//div[./span[contains(text(), "活动门槛价")]]/span[2]/span[2]'; // 另一种活动申报价元素路径，包含门槛价和最优流量价
  } else {
    // 如果不是支持的页面类型，则退出函数
    return;
  }
  
  // console.log("开始处理活动营销日志页面数据...");
  
  // 获取表格中的所有数据行
  const rows = document.evaluate(
    '//tbody[@data-testid="beast-core-table-middle-tbody"]/tr',
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );
  
  // 用于记录当前处理的SKC，子行会使用主行的SKC
  let currentSkc = null;

  let skuCostsAndInventories = null; // 用于缓存所有SKU的成本价和库存信息，避免重复请求
  
  // 遍历表格中的每一行数据
  for (let i = 0; i < rows.snapshotLength; i++) {
    const row = rows.snapshotItem(i);
    // 获取当前行中的所有单元格
    const tdElements = document.evaluate('./td', row, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
    // 声明变量用于存储当前行的SKC、SKU和价格信息
    let skc, sku, regularPrice, activityPrice;
    let skuElement, regularPriceElement, activityPriceElement, activityPriceElement_2;
    let hasCostInfo = false;

    // 根据单元格数量判断是主行还是子行
    // 主行包含完整的SKC信息，子行只包含SKU变体信息
    if (tdElements.snapshotLength > 5) {
      // 主行处理：包含SKC信息，列数较多
      // 使用XPath获取各个元素
      const skcElement = document.evaluate(`./td[${tdIdx_skc}]${xpath_skc}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      skuElement = document.evaluate(`./td[${tdIdx_sku_main}]${xpath_sku}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      regularPriceElement = document.evaluate(`./td[${tdIdx_regularPrice_main}]${xpath_regularPrice}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      activityPriceElement = document.evaluate(`./td[${tdIdx_activityPrice_main}]${xpath_activityPrice}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      activityPriceElement_2 = document.evaluate(`./td[${tdIdx_activityPrice_main}]${xpath_activityPrice_2}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      hasCostInfo = !!document.evaluate(`./td[${tdIdx_activityPrice_main}]${xpath_span_cost}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      
      // 如果找到SKC元素，更新当前SKC值
      if (skcElement) {
        currentSkc = skcElement.textContent.trim();
        skc = currentSkc;
      }
    } else {
      // 子行处理：使用主行的SKC信息，列数较少
      skc = currentSkc; // 继承主行的SKC
      // 子行中各元素的位置不同
      skuElement = document.evaluate(`./td[${tdIdx_sku_sub}]${xpath_sku}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      regularPriceElement = document.evaluate(`./td[${tdIdx_regularPrice_sub}]${xpath_regularPrice}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      activityPriceElement = document.evaluate(`./td[${tdIdx_activityPrice_sub}]${xpath_activityPrice}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      activityPriceElement_2 = document.evaluate(`./td[${tdIdx_activityPrice_sub}]${xpath_activityPrice_2}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      hasCostInfo = !!document.evaluate(`./td[${tdIdx_activityPrice_sub}]${xpath_span_cost}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    }

    if (hasCostInfo) {
      // 如果已经存在成本信息，跳过该行
      continue;
    }

    if (!skuCostsAndInventories) {
      skuCostsAndInventories = await getAllSkuCostAndInventory();
    }

    // 提取SKU信息，并处理格式
    if (skuElement) {
      sku = skuElement.textContent.trim();
      // 删除开头的"货号:"字符串（如果存在）
      sku = sku.replace(/^货号:/, "");
    }
    
    // 获取日常申报价格元素
    if (regularPriceElement) {
      regularPrice = regularPriceElement;
    }
    
    // 获取活动申报价格元素
    if (activityPriceElement) {
      activityPrice = activityPriceElement;
    } else if (activityPriceElement_2) {
      activityPrice = activityPriceElement_2;
    }
    
    // 只有当同时获取到SKC、SKU和至少一种价格信息时，才获取成本价
    if (skc && sku && (regularPrice || activityPrice)) {
      try {
        // 使用Chrome扩展消息传递机制向后台脚本请求SKU的成本价
        // 通过sendMessage发送请求，action为'getSkuCost'
        // const data = await new Promise((resolve) => {
        //   chrome.runtime.sendMessage(
        //     { 
        //       action: 'getSkuCost',  // 请求类型：获取SKU成本
        //       skc: skc,              // 传递SKC编号
        //       sku: sku               // 传递SKU编号
        //     }, 
        //     (response) => {
        //       // 处理响应结果，如果没有响应则返回空对象
        //       resolve(response || {});
        //     }
        //   );
        // });

        const data = skuCostsAndInventories[`${skc}_${sku}`];

        
        // 检查是否成功获取到成本价数据
        if (data && data.cost !== undefined) {
          const cost = parseFloat(data.cost); // 将成本价转换为浮点数
          const inventory = data.inventory; // 获取库存信息（如果需要）
          
          // 更新日常申报价显示（如果存在）
          if (regularPrice) {
            // 检查是否已经添加了成本和毛利信息（避免重复添加）
            const existingCostInfo = regularPrice.parentNode.querySelector('span[style*="margin-left: 5px"]');
            if (!existingCostInfo) {
              const regularPriceValue = parseFloat(regularPrice.textContent); // 获取日常申报价
              // 计算毛利率：(售价-成本)/售价*100%，保留0位小数
              const regularMargin = ((regularPriceValue - cost) / regularPriceValue * 100).toFixed(0);
              
              // 创建成本价和毛利润率显示元素
              const costInfoSpan = document.createElement('span');
              // 根据毛利率设置颜色：大于10%为绿色，否则为红色
              costInfoSpan.style.color = (parseFloat(regularMargin) > 10 && inventory > 0) ? 'green' : 'red';
              costInfoSpan.style.marginLeft = '5px'; // 设置左边距
              costInfoSpan.textContent = `(成本:${cost.toFixed(2)}, 毛利:${regularMargin}%, 库存:${inventory})`; // 设置显示内容
              
              // 将成本和毛利信息添加到日常申报价后面
              regularPrice.parentNode.appendChild(costInfoSpan);
            }
          }
          
          // 更新活动申报价显示（如果存在）
          if (activityPrice) {
            // 检查是否已经添加了成本和毛利信息（避免重复添加）
            const existingCostInfo = activityPrice.parentNode.querySelector('span[style*="margin-left: 5px"]');
            if (!existingCostInfo) {
              const activityPriceValue = parseFloat(activityPrice.textContent); // 获取活动申报价
              // 计算毛利率：(售价-成本)/售价*100%，保留0位小数
              const activityMargin = ((activityPriceValue - cost) / activityPriceValue * 100).toFixed(0);
              
              // 创建成本价和毛利润率显示元素
              const costInfoSpan = document.createElement('span');
              // 根据毛利率设置颜色：大于10%为绿色，否则为红色
              costInfoSpan.style.color = parseFloat(activityMargin) > 10 ? 'green' : 'red';
              costInfoSpan.style.marginLeft = '5px'; // 设置左边距
              costInfoSpan.textContent = `(成本:${cost.toFixed(2)}, 毛利:${activityMargin}%)`; // 设置显示内容
              
              // 将成本和毛利信息添加到活动申报价后面
              activityPrice.parentNode.appendChild(costInfoSpan);
            }
          }
        } else {
          // 如果未获取到成本价数据，记录日志
          console.log(`未获取到SKU ${sku} 的成本价`);
        }
      } catch (error) {
        // 捕获并记录获取成本价过程中的错误
        console.error(`获取SKU ${sku} 成本价时出错:`, error);
      }
    }
  }
  
  // 处理完成后记录日志
  // console.log("活动营销日志页面数据处理完成");

  setTimeout(processMarketingActivityLog, 5000); // 每5秒处理一次，处理完再设置定时器，避免重复处理
}

/**
 * 获取当前活动报名或者列表页面所有SKU的成本价和库存
 */
async function getAllSkuCostAndInventory() {
  // 定义表格中各列的索引和XPath，不同页面有不同的结构
  let tdIdx_skc;                                      // SKC信息所在列索引
  let tdIdx_sku_main;  // 主行中各列索引
  let tdIdx_sku_sub;     // 子行中各列索引
  let xpath_skc, xpath_sku;      // 各元素的XPath

  // 处理活动营销日志页面 - 固定列结构
  if (window.location.href.startsWith("https://agentseller.temu.com/activity/marketing-activity/log")) {
    // 设置活动日志页面的列索引（固定结构）
    tdIdx_skc = 3;                    // SKC信息在第3列
    tdIdx_sku_main = 4;               // 主行中SKU在第4列
    tdIdx_sku_sub = 1;                // 子行中SKU在第1列

    // 设置各元素在单元格内的XPath
    xpath_skc = '/div/div/div[1]';            // SKC信息元素路径
    xpath_sku = '/div/div/div';               // SKU信息元素路径
  // 处理活动详情页面 - 动态列结构
  } else if (window.location.href.startsWith("https://agentseller.temu.com/activity/marketing-activity/detail-new")) {
    // 从表头动态获取各列的索引，因为详情页面的列顺序可能会变化
    const headers = document.evaluate(
      '//thead[@data-testid="beast-core-table-middle-thead"]/tr/th',
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
    );
    
    // 遍历表头，根据列名确定各列的索引
    for (let i = 0; i < headers.snapshotLength; i++) {
      const headerText = headers.snapshotItem(i).textContent.trim();
      if (headerText === "SKC信息") {
        tdIdx_skc = i + 1;                // XPath索引从1开始，而不是0
      } else if (headerText === "SKU属性集") {
        tdIdx_sku_main = i + 1;           // SKU属性集列索引
      }
    }
    
    // 子行的列索引是固定的
    tdIdx_sku_sub = 1;                // 子行中SKU在第1列

    // 详情页面中各元素的XPath与日志页面略有不同
    xpath_skc = '/div/div[1]';             // SKC信息元素路径
    xpath_sku = '/div/div[2]';             // SKU信息元素路径
  } else {
    // 如果不是支持的页面类型，则退出函数
    return;
  }
 
  // 获取表格中的所有数据行
  const rows = document.evaluate(
    '//tbody[@data-testid="beast-core-table-middle-tbody"]/tr',
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );
  
  // 用于记录当前处理的SKC，子行会使用主行的SKC
  let currentSkc = null;
  
  let skuList = []; // 用于存储所有SKU信息的数组
  // 遍历表格中的每一行数据
  for (let i = 0; i < rows.snapshotLength; i++) {
    const row = rows.snapshotItem(i);
    // 获取当前行中的所有单元格
    const tdElements = document.evaluate('./td', row, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    
    // 声明变量用于存储当前行的SKC、SKU和价格信息
    let skc, sku;
    let skuElement;

    // 根据单元格数量判断是主行还是子行
    // 主行包含完整的SKC信息，子行只包含SKU变体信息
    if (tdElements.snapshotLength > 5) {
      // 主行处理：包含SKC信息，列数较多
      // 使用XPath获取各个元素
      const skcElement = document.evaluate(`./td[${tdIdx_skc}]${xpath_skc}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      skuElement = document.evaluate(`./td[${tdIdx_sku_main}]${xpath_sku}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      
      // 如果找到SKC元素，更新当前SKC值
      if (skcElement) {
        currentSkc = skcElement.textContent.trim();
        skc = currentSkc;
      }
    } else {
      // 子行处理：使用主行的SKC信息，列数较少
      skc = currentSkc; // 继承主行的SKC
      // 子行中各元素的位置不同
      skuElement = document.evaluate(`./td[${tdIdx_sku_sub}]${xpath_sku}`, row, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    }

    // 提取SKU信息，并处理格式
    if (skuElement) {
      sku = skuElement.textContent.trim();
      // 删除开头的"货号:"字符串（如果存在）
      sku = sku.replace(/^货号:/, "");
    }

    skuList.push({ skc, sku }); // 将SKC和SKU添加到数组中
  }

  skuCosts = await fetchSkuCostsAndStocks(skuList);

  return skuCosts;
}

async function fetchSkuCostsAndStocks(skuList) { 
  if (skuList.length === 0) {
    return {};
  }
  const data = await new Promise((resolve) => {
    chrome.runtime.sendMessage(
      { 
        action: 'getSkuCostsAndStocks',  // 请求类型：获取SKU成本
        skuList               // 传递SKU编号
      }, 
      (response) => {
        // 处理响应结果，如果没有响应则返回空对象
        resolve(response || {});
      }
    );
  });

  return data;
}

// 添加load事件监听作为后备
window.addEventListener('load', () => {
  console.log('Window load event received');
  setInterval(updateRealtimeSold, 5000);
  
  // 延时5秒后执行活动营销日志页面处理
  setTimeout(processMarketingActivityLog, 5000);
});